package com.tdtxdcxm.ruralcommunity.slice;

import com.tdtxdcxm.ruralcommunity.ResourceTable;
import com.tdtxdcxm.ruralcommunity.appruntime.DataCenterControl;
import com.tdtxdcxm.ruralcommunity.httpmanagers.ThreadPoolUtil;
import com.tdtxdcxm.ruralcommunity.items.LCArryListNormalItem;
import com.tdtxdcxm.ruralcommunity.myutils.MyTools;
import com.tdtxdcxm.ruralcommunity.providers.LCProviderForNormal;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;
import ohos.utils.zson.ZSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ContentDiscussSlice extends AbilitySlice {
    private String contentid;
    private Button discuss_backbut,discuss_gobut;
    private TextField discuss_writetfd;
    private ListContainer discuss_lc;

    /*<****************http请求内容评论数据区域*****************/
    public void DownDataContentDiscussListInfo(String contentid){
        NetManager main_toplistnetmanger = NetManager.getInstance(this.getContext());
        if (!main_toplistnetmanger.hasDefaultNet()) {
            return;
        }
        ThreadPoolUtil.submit(() -> {
            NetHandle thenetHandle = main_toplistnetmanger.getDefaultNet();
            NetStatusCallback netStatusCallback = new NetStatusCallback() {};
            HttpURLConnection httpURLConnection = null;

            String urlString = DataCenterControl.serverIpWithPort + "pulldiscuss/?";
            try {
                URL url = new URL(urlString);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                URLConnection urlConnection = thenetHandle.openConnection(url, java.net.Proxy.NO_PROXY);
                if (urlConnection instanceof HttpURLConnection) {
                    httpURLConnection = (HttpURLConnection) urlConnection;
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("contentid=");
                    stringBuilder.append(contentid);

                    byte[] b = stringBuilder.toString().getBytes();
                    httpURLConnection.getOutputStream().write(b);

                    try {
                        httpURLConnection.connect();
                    } catch (IOException e) {}
                    outputStream.flush();

                    InputStream inputStream = null;
                    try {
                        inputStream = urlConnection.getInputStream();
                        byte[] cache = new byte[2 * 1024];
                        int len = inputStream.read(cache);
                        while (len != -1) {
                            outputStream.write(cache, 0, len);
                            len = inputStream.read(cache);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = "";
                    result = outputStream.toString();
                    if(result.indexOf("sum") != -1){
                        String finalResult = result;
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                    ZSONObject zsonobject_dt = ZSONObject.stringToZSON(finalResult);
                                    int sum_dt = Integer.parseInt(zsonobject_dt.getString("sum"));
                                    DataCenterControl.discuss_listcontainer_list.clear();
                                    for(int i = 0;i < sum_dt;i++){
                                        ZSONObject t = ZSONObject.stringToZSON(zsonobject_dt.getString(String.valueOf(i)));
                                        DataCenterControl.discuss_listcontainer_list.add(new LCArryListNormalItem(t.getString("detail")));
                                    }

                                    if(DataCenterControl.discussListContainerProvider != null){
                                        DataCenterControl.discussListContainerProvider.notifyDataChanged();
                                    }
                                    MyTools.toastShow("内容评论下载成功！", ContentDiscussSlice.this.getContext());
                            }
                        });
                    }
                    else if(result.equals("NULL")){
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                    DataCenterControl.discuss_listcontainer_list.clear();
                                    if(DataCenterControl.discussListContainerProvider != null){
                                        DataCenterControl.discussListContainerProvider.notifyDataChanged();
                                    }
                                    MyTools.toastShow("评论为空！", ContentDiscussSlice.this.getContext());
                            }
                        });
                    }
                    else{
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                MyTools.toastShow("该内容评论下载失败！", ContentDiscussSlice.this.getContext());
                            }
                        });
                    }
                }
            } catch (IOException e) {
            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        });
    }
    /******************http请求内容评论数据区域***************>*/

    /*<****************http发布评论数据区域*****************/
    public void UpDataContentDiscussInfo(String contentid,String detail){
        NetManager main_toplistnetmanger = NetManager.getInstance(this.getContext());
        if (!main_toplistnetmanger.hasDefaultNet()) {
            return;
        }
        ThreadPoolUtil.submit(() -> {
            NetHandle thenetHandle = main_toplistnetmanger.getDefaultNet();
            NetStatusCallback netStatusCallback = new NetStatusCallback() {};
            HttpURLConnection httpURLConnection = null;

            String urlString = DataCenterControl.serverIpWithPort + "pushdiscuss/?";
            try {
                URL url = new URL(urlString);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                URLConnection urlConnection = thenetHandle.openConnection(url, java.net.Proxy.NO_PROXY);
                if (urlConnection instanceof HttpURLConnection) {
                    httpURLConnection = (HttpURLConnection) urlConnection;
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("username=");
                    stringBuilder.append(DataCenterControl.userName);
                    stringBuilder.append("&contentid=");
                    stringBuilder.append(contentid);
                    stringBuilder.append("&detail=");
                    stringBuilder.append(detail);
                    stringBuilder.append("&time=");
                    SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(System.currentTimeMillis());
                    stringBuilder.append(formatter.format(date));

                    byte[] b = stringBuilder.toString().getBytes();
                    httpURLConnection.getOutputStream().write(b);

                    try {
                        httpURLConnection.connect();
                    } catch (IOException e) {}
                    outputStream.flush();


                    InputStream inputStream = null;
                    try {
                        inputStream = urlConnection.getInputStream();
                        byte[] cache = new byte[2 * 1024];
                        int len = inputStream.read(cache);
                        while (len != -1) {
                            outputStream.write(cache, 0, len);
                            len = inputStream.read(cache);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = "";
                    result = outputStream.toString();
                    if(result.equals("OK")){
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                discuss_writetfd.clearFocus();
                                discuss_writetfd.setText("");
                                MyTools.toastShow("评论成功！", ContentDiscussSlice.this.getContext());
                            }
                        });
                    }
                    else if(result.equals("NO")){
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                MyTools.toastShow("评论失败！！", ContentDiscussSlice.this.getContext());
                            }
                        });
                    }
                }
            } catch (IOException e) {
            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        });
    }
    /******************http发布评论数据区域***************>*/

    /*<----------------------------------------初始化ListContainer区域----------------------------------*/
    public void initListContainer(ListContainer listContainer,String listContainerName,AbilitySlice slice){
        if(listContainer == null){
            return;
        }
        listContainer.setName(listContainerName);
        LCProviderForNormal lcProviderForNormal = new LCProviderForNormal(DataCenterControl.discuss_listcontainer_list,this);
        DataCenterControl.discussListContainerProvider = lcProviderForNormal;

        if(lcProviderForNormal != null){
            listContainer.setItemProvider(lcProviderForNormal);
        }

    }
    /*-----------------------------------------初始化ListContainer区域---------------------------------->*/


    private void initCDSComponents(){
        discuss_backbut = (Button) findComponentById(ResourceTable.Id_discuss_backbut);
        discuss_gobut = (Button) findComponentById(ResourceTable.Id_discuss_gobut);
        discuss_writetfd = (TextField) findComponentById(ResourceTable.Id_discuss_writetfd);
        discuss_lc = (ListContainer) findComponentById(ResourceTable.Id_discuss_lc);

        discuss_backbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                DataCenterControl.discuss_listcontainer_list.clear();
                discuss_writetfd.clearFocus();
                discuss_writetfd.setText("");
                terminate();
            }
        });
        discuss_gobut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(discuss_writetfd.getText().equals("")){
                    MyTools.toastShow("评论内容不能为空！",ContentDiscussSlice.this.getContext());
                    return;
                }
                UpDataContentDiscussInfo(contentid,discuss_writetfd.getText());
            }
        });
        discuss_writetfd.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if(s.length() > 299){
                    discuss_writetfd.setText(s.substring(0,s.length() - 1));
                    MyTools.toastShow("不能超过300字！",ContentDiscussSlice.this.getContext());
                }
            }
        });

        initListContainer(discuss_lc,"discusslc",this);
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_usercontent_discuss);
        initCDSComponents();
        contentid = intent.getStringParam("contentid");
        DownDataContentDiscussListInfo(contentid);
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
